package cn.controller;

import cn.pojo.Lesson;
import cn.service.CourseClickService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 课程点击Controller
 */
@Controller("COURSECLICK")
@RequestMapping("/")
public class CourseClickController {

    //页面跳转
    @RequestMapping("/courseClick")
    public String toGetCourseClick(){
        return "courseClick";
    }

    /**
     *  sponseBody注解的作用是将controller的方法返回的对象通过适当的转换器转
     *  换为指定的格式之后，写入到response对象的body区，通常用来返回JSON数据或者是XML
     */
    @ResponseBody
    @RequestMapping(value = "/getCourseClickCount",method = RequestMethod.GET)
    public JSONArray courseClickCount(String data){
        JSONArray json = new JSONArray();
        //如果url没有传值，传入一个默认值
//       Lesson类有课程名name(String)和对应的人点击量count(int)
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "beans.xml");
        CourseClickService service = (CourseClickService) context.getBean("clickService");
        Lesson use = (Lesson) context.getBean("Lesson");
        List<Lesson> lessons = service.selectLessonALlSer(use);
        for(Lesson les : lessons){
            JSONObject jo = new JSONObject();
            jo.put("name",les.getLesson());
            jo.put("count",les.getLesson_count());

            json.add(jo);
        }
//      list有多个课程名和对应的点击量
        //封装JSON数据
        return json;
    }
}